import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/features/profile/viewmodels/profile_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/vacant_state.dart';
import 'package:vista/main.dart' as app;

/// 个人视图
/// 个人功能页面
class ProfileView extends StatefulWidget {
  const ProfileView({super.key});

  @override
  State<ProfileView> createState() => _ProfileViewState();
}

class _ProfileViewState extends State<ProfileView>
    with WidgetsBindingObserver, RouteAware {
  final PageController _pageController = PageController();
  int _currentPage = 0;
  ProfileViewModel? _viewModel;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route is PageRoute) {
      app.routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    app.routeObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    _pageController.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台恢复时，刷新登录状态
    if (state == AppLifecycleState.resumed && _viewModel != null) {
      _viewModel!.refresh();
    }
  }

  @override
  void didPopNext() {
    // 当从其他页面返回到此页面时刷新
    if (_viewModel != null) {
      _viewModel!.refresh();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ProfileViewModel>.reactive(
      viewModelBuilder:
          () =>
              ProfileViewModel(getIt.get(), getIt.get(), getIt.get())
                ..initialize(),
      onViewModelReady: (viewModel) {
        _viewModel = viewModel;
      },
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child:
                  viewModel.isBusy
                      ? const Center(child: CircularProgressIndicator())
                      : viewModel.currentUser == null
                      ? _buildLoginPrompt(context, viewModel)
                      : _buildContent(context, viewModel),
            ),
          ),
        );
      },
    );
  }

  /// 构建登录提示
  Widget _buildLoginPrompt(BuildContext context, ProfileViewModel viewModel) {
    return [
          VacantState(
            message: 'Please login to view profile',
            imagePath: 'assets/images/empty1.png',
          ),
          SizedBox(height: 32.h),
          // 登录按钮
          ElevatedButton(
            onPressed: () async {
              await Navigator.of(context).pushNamed(Routes.login);
              if (mounted) {
                await viewModel.refresh();
              }
            },
            style: ElevatedButton.styleFrom(
              padding: EdgeInsets.symmetric(horizontal: 48.w, vertical: 16.h),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.r),
              ),
              backgroundColor: ColorConstants.accentColor,
              foregroundColor: Colors.white,
              elevation: 0,
            ),
            child: Text(
              'Login',
              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
            ),
          ),
        ]
        .verticalShot(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
        )
        .frameHorizontal(24.w);
  }

  /// 构建内容
  Widget _buildContent(BuildContext context, ProfileViewModel viewModel) {
    return Stack(
      children: [
        // 可滚动的内容
        SingleChildScrollView(
          child: [
            SizedBox(height: 20.h),
            // 用户信息和数据统计
            _buildUserInfoSection(context, viewModel).frameHorizontal(14.w),
            SizedBox(height: 20.h),
            // 页面指示器和 page 区域的白色背景 container（全宽，无左右边距）
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16.r),
                  topRight: Radius.circular(16.r),
                ),
              ),
              child: [
                SizedBox(height: 14.h),
                // 页面指示器
                _buildPageIndicator(context).frameHorizontal(14.w),
                SizedBox(height: 14.h),
                // 两个 page（不能滑动，高度一致）
                _buildPagesSection(context, viewModel).frameHorizontal(14.w),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
            SizedBox(height: 100.h), // 底部留白
          ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
        ),
        // 顶部固定的设置按钮（不占据位置）
        Positioned(
          top: 0,
          right: 14.w,
          child: SafeArea(
            child: Padding(
              padding: EdgeInsets.only(top: 16.h),
              child: GestureDetector(
                onTap: () {
                  Navigator.of(context).pushNamed(Routes.settings);
                },
                child: Image.asset(
                  'assets/images/setup.png',
                  width: 28.w,
                  height: 28.h,
                  fit: BoxFit.contain,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建用户信息和数据统计区域
  Widget _buildUserInfoSection(
    BuildContext context,
    ProfileViewModel viewModel,
  ) {
    final user = viewModel.currentUser!;

    final avatarRadius = 40.r;

    return Stack(
      clipBehavior: Clip.none,
      children: [
        // Container 主体
        Container(
          margin: EdgeInsets.only(top: avatarRadius), // 为头像留出空间
          decoration: BoxDecoration(
            gradient: const LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFFFFEBE6), Color(0xFFFFA680)],
            ),
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(color: Colors.black.withOpacity(0.1), width: 1),
          ),
          padding: EdgeInsets.fromLTRB(14.w, avatarRadius + 14.h, 14.w, 14.w),
          child: [
            // 用户名和签名（居中）
            Center(
              child: GestureDetector(
                onTap: () async {
                  final result = await Navigator.of(
                    context,
                  ).pushNamed(Routes.editProfile);
                  // 返回时刷新数据
                  if (result == true && context.mounted) {
                    await viewModel.refresh();
                  }
                },
                child: [
                  // 用户名和编辑图标
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        user.username,
                        style: TextStyle(
                          fontSize: 20.sp,
                          fontWeight: FontWeight.w800,
                          fontFamily:
                              GoogleFonts.alegreyaSans(
                                fontWeight: FontWeight.w800,
                              ).fontFamily,
                          color: Colors.black,
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Image.asset(
                        'assets/images/edit.png',
                        width: 14.w,
                        height: 14.w,
                      ),
                    ],
                  ),
                  if (user.signature != null) ...[
                    Text(
                      user.signature!,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.black,
                        fontFamily:
                            GoogleFonts.alegreyaSans(
                              fontWeight: FontWeight.w500,
                            ).fontFamily,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.center,
                    ),
                  ],
                ].verticalShot(crossAxisAlignment: CrossAxisAlignment.center),
              ),
            ),
            SizedBox(height: 20.h),
            // 数据统计
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem('Posts', '${viewModel.postCount}'),
                _buildStatItem('Likes', '${viewModel.likeCount}'),
                _buildStatItem('Friends', '${viewModel.friendCount}'),
              ],
            ),
          ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
        ),
        // 用户头像（一半在 container 外面，居中）
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: Center(
            child: CircleAvatar(
              radius: avatarRadius,
              backgroundColor: ColorConstants.primaryColor,
              backgroundImage:
                  user.avatar != null ? AssetImage(user.avatar!) : null,
              child:
                  user.avatar == null
                      ? Icon(Icons.person, size: 40.w, color: Colors.white)
                      : null,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value) {
    return [
      Text(
        value,
        style: TextStyle(
          fontSize: 24.sp,
          fontWeight: FontWeight.w800,
          fontFamily:
              GoogleFonts.alegreyaSans(fontWeight: FontWeight.w800).fontFamily,
          color: Colors.black87,
        ),
      ),
      SizedBox(height: 4.h),
      Text(
        label,
        style: TextStyle(
          fontSize: 14.sp,
          fontFamily:
              GoogleFonts.alegreyaSans(fontWeight: FontWeight.w400).fontFamily,
          color: Colors.black54,
        ),
      ),
    ].verticalShot(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
    );
  }

  /// 构建页面指示器
  Widget _buildPageIndicator(BuildContext context) {
    return Row(
      children: [
        GestureDetector(
          onTap: () {
            _pageController.animateToPage(
              0,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
            decoration: BoxDecoration(
              color:
                  _currentPage == 0
                      ? ColorConstants.accentColor
                      : Colors.transparent,
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  'assets/images/post.png',
                  width: 16.w,
                  height: 16.w,
                  color: _currentPage == 0 ? Colors.white : Colors.black54,
                ),
                SizedBox(width: 6.w),
                Text(
                  'My Posts',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                    color: _currentPage == 0 ? Colors.white : Colors.black54,
                  ),
                ),
              ],
            ),
          ),
        ),
        SizedBox(width: 16.w),
        GestureDetector(
          onTap: () {
            _pageController.animateToPage(
              1,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
            decoration: BoxDecoration(
              color:
                  _currentPage == 1
                      ? ColorConstants.accentColor
                      : Colors.transparent,
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(
                  'assets/images/like.png',
                  width: 16.w,
                  height: 16.w,
                  color: _currentPage == 1 ? Colors.white : Colors.black54,
                ),
                SizedBox(width: 6.w),
                Text(
                  'Liked Posts',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                    color: _currentPage == 1 ? Colors.white : Colors.black54,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建两个 page 区域
  Widget _buildPagesSection(BuildContext context, ProfileViewModel viewModel) {
    // 计算两个 page 的最大高度
    final myPostsHeight = _calculateMyPostsHeight(viewModel.myPosts);
    final likedPostsHeight = _calculateLikedPostsHeight(viewModel.likedPosts);
    final maxHeight =
        myPostsHeight > likedPostsHeight ? myPostsHeight : likedPostsHeight;

    return SizedBox(
      height: maxHeight,
      child: PageView(
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _currentPage = index;
          });
        },
        physics: const NeverScrollableScrollPhysics(), // 禁止滑动
        children: [
          // 我发布的动态列表
          _buildMyPostsPage(context, viewModel),
          // 我点赞的动态列表
          _buildLikedPostsPage(context, viewModel),
        ],
      ),
    );
  }

  /// 计算我发布的动态列表高度
  double _calculateMyPostsHeight(List<MomentShot> posts) {
    if (posts.isEmpty) {
      return 200.h + 400.h; // 空状态高度 + 固定底部空间
    }
    // 每个项的高度 = 宽度 * (235 / 167)
    // 宽度计算：屏幕宽度 - 页面左右边距(14*2) - 项之间间距(14) 然后除以2
    final screenWidth = MediaQuery.of(context).size.width;
    final itemWidth = (screenWidth - 14.w * 2 - 14.w) / 2;
    final itemHeight = itemWidth * (235 / 167);
    final rows = (posts.length / 2).ceil();
    return rows * itemHeight + (rows - 1) * 14.h; // 加上间距
  }

  /// 计算点赞的动态列表高度
  double _calculateLikedPostsHeight(List<MomentShot> posts) {
    if (posts.isEmpty) {
      return 200.h + 400.h; // 空状态高度 + 固定底部空间
    }
    // 每个项的高度 = 宽度 * (300 / 347)
    final screenWidth = MediaQuery.of(context).size.width;
    final itemWidth = screenWidth - 14.w * 2; // 减去页面左右边距
    final itemHeight = itemWidth * (300 / 347);
    return posts.length * itemHeight + (posts.length - 1) * 14.h;
  }

  /// 构建我发布的动态列表页面
  Widget _buildMyPostsPage(BuildContext context, ProfileViewModel viewModel) {
    if (viewModel.myPosts.isEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Padding(
            padding: EdgeInsets.only(top: 20.h),
            child: VacantState(
              message: 'No posts yet',
              imagePath: 'assets/images/empty2.png',
            ),
          ),
          Expanded(
            child: SizedBox.shrink(), // 填充剩余空间
          ),
        ],
      );
    }

    return SingleChildScrollView(
      physics: const NeverScrollableScrollPhysics(), // 禁止滑动
      child: [
        // 网格布局
        Wrap(
          spacing: 14.w,
          runSpacing: 14.h,
          children: [
            for (final post in viewModel.myPosts)
              _buildMyPostItem(context, viewModel, post),
          ],
        ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建我发布的单个动态项
  Widget _buildMyPostItem(
    BuildContext context,
    ProfileViewModel viewModel,
    MomentShot post,
  ) {
    final itemWidth =
        (MediaQuery.of(context).size.width - 14.w * 2 - 14.w) /
        2; // 减去页面左右边距(14*2)和项之间间距(14)
    final itemHeight = itemWidth * (235 / 167);

    return SizedBox(
      width: itemWidth,
      height: itemHeight,
      child: GestureDetector(
        onTap: () async {
          // 根据动态类型跳转到对应的详情页
          final route =
              post.category == PostCategory.dailyLife
                  ? Routes.momentDetail
                  : Routes.photographyDetail;
          await Navigator.of(
            context,
          ).pushNamed(route, arguments: {'postId': post.id});
          await viewModel.refresh();
        },
        child: Stack(
          children: [
            // 背景图片（第一张图片）
            ClipRRect(
              borderRadius: BorderRadius.circular(6.r),
              child:
                  post.images.isNotEmpty
                      ? Image.asset(
                        post.images[0],
                        width: double.infinity,
                        height: double.infinity,
                        fit: BoxFit.cover,
                      )
                      : Container(color: Colors.grey[300]),
            ),
            // 右上角删除按钮
            Positioned(
              top: 8.h,
              right: 8.w,
              child: GestureDetector(
                onTap: () => _showDeleteDialog(context, viewModel, post),
                child: Image.asset(
                  'assets/images/delete2.png',
                  width: 22.w,
                  height: 22.w,
                  color: Colors.white,
                ),
              ),
            ),
            // 左下角查看次数
            Positioned(
              bottom: 8.h,
              left: 8.w,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  borderRadius: BorderRadius.circular(4.r),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      'assets/images/eye.png',
                      width: 14.w,
                      height: 14.w,
                      color: Colors.white,
                    ),
                    SizedBox(width: 4.w),
                    Text(
                      '${post.viewCount}',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示删除确认弹窗
  Future<void> _showDeleteDialog(
    BuildContext context,
    ProfileViewModel viewModel,
    MomentShot post,
  ) async {
    final result = await showDialog<bool>(
      context: context,
      builder:
          (context) => Dialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.r),
            ),
            insetPadding: EdgeInsets.symmetric(
              horizontal: 40.w,
              vertical: 80.h,
            ),
            elevation: 0,
            backgroundColor: Colors.transparent,
            child: Container(
              constraints: BoxConstraints(maxWidth: 320.w, minWidth: 280.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20.r),
                gradient: const LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [Color(0xFFFFA680), Color(0xFFFFEBE6)],
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20.w,
                    offset: Offset(0, 10.h),
                  ),
                ],
              ),
              child: [
                    // 标题
                    Text(
                      'Delete Post',
                      style: TextStyle(
                        fontSize: 22.sp,
                        fontWeight: FontWeight.w800,
                        fontFamily:
                            GoogleFonts.alegreyaSans(
                              fontWeight: FontWeight.w800,
                            ).fontFamily,
                        color: Colors.black87,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 16.h),
                    // 描述
                    Text(
                      'Are you sure you want to delete this post?',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.black.withOpacity(0.7),
                        height: 1.5,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    SizedBox(height: 36.h),
                    // 按钮组
                    [
                      // 取消按钮
                      Expanded(
                        child: OutlinedButton(
                          onPressed: () => Navigator.of(context).pop(false),
                          style: OutlinedButton.styleFrom(
                            padding: EdgeInsets.symmetric(vertical: 16.h),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                            side: BorderSide(
                              color: Colors.black.withOpacity(0.2),
                              width: 1.5,
                            ),
                          ),
                          child: Text(
                            'Cancel',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.black87,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 14.w),
                      // 删除按钮
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () => Navigator.of(context).pop(true),
                          style: ElevatedButton.styleFrom(
                            padding: EdgeInsets.symmetric(vertical: 16.h),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12.r),
                            ),
                            backgroundColor: Colors.red,
                            foregroundColor: Colors.white,
                            elevation: 0,
                          ),
                          child: Text(
                            'Delete',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ].horizontalGallery(),
                  ]
                  .verticalShot(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                  )
                  .frameAll(32.w),
            ),
          ),
    );

    if (result == true && context.mounted) {
      await viewModel.deletePost(post.id);
      await viewModel.refresh();
      // 显示删除成功提示
      FlashNotifier.flashSuccess('Post deleted successfully');
    }
  }

  /// 构建我点赞的动态列表页面
  Widget _buildLikedPostsPage(
    BuildContext context,
    ProfileViewModel viewModel,
  ) {
    if (viewModel.likedPosts.isEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Padding(
            padding: EdgeInsets.only(top: 20.h),
            child: VacantState(
              message: 'No liked posts yet',
              imagePath: 'assets/images/empty2.png',
            ),
          ),
          Expanded(
            child: SizedBox.shrink(), // 填充剩余空间
          ),
        ],
      );
    }

    return SingleChildScrollView(
      physics: const NeverScrollableScrollPhysics(), // 禁止滑动
      child: [
        for (int i = 0; i < viewModel.likedPosts.length; i++) ...[
          _buildLikedPostItem(context, viewModel, viewModel.likedPosts[i]),
          if (i < viewModel.likedPosts.length - 1) SizedBox(height: 14.h),
        ],
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
    );
  }

  /// 构建点赞的单个动态项（参考社区页面样式）
  Widget _buildLikedPostItem(
    BuildContext context,
    ProfileViewModel viewModel,
    MomentShot post,
  ) {
    // 获取作者信息
    final author = viewModel.getUserById(post.authorId);

    return GestureDetector(
      onTap: () async {
        // 根据动态类型跳转到对应的详情页
        final route =
            post.category == PostCategory.dailyLife
                ? Routes.momentDetail
                : Routes.photographyDetail;
        await Navigator.of(
          context,
        ).pushNamed(route, arguments: {'postId': post.id});
        await viewModel.refresh();
      },
      child: AspectRatio(
        aspectRatio: 347 / 300,
        child: Stack(
          children: [
            // 背景图片
            Container(
              decoration: BoxDecoration(
                image: const DecorationImage(
                  image: AssetImage('assets/images/daily-routine.png'),
                  fit: BoxFit.fill,
                ),
                borderRadius: BorderRadius.circular(6.r),
                boxShadow: [
                  BoxShadow(
                    color: ColorConstants.blackColor,
                    blurRadius: 0,
                    offset: Offset(2, 2),
                    spreadRadius: 0,
                  ),
                ],
              ),
            ),
            // 内容
            Padding(
              padding: EdgeInsets.only(
                left: 14.w,
                right: 14.w,
                top: 32.w,
                bottom: 27.h,
              ),
              child: [
                // 用户信息行
                Row(
                  children: [
                    // 用户头像
                    CircleAvatar(
                      radius: 20.r,
                      backgroundColor: ColorConstants.primaryColor,
                      backgroundImage:
                          author?.avatar != null
                              ? AssetImage(author!.avatar!)
                              : null,
                      child:
                          author?.avatar == null
                              ? Icon(
                                Icons.person,
                                size: 20.w,
                                color: Colors.white,
                              )
                              : null,
                    ),
                    SizedBox(width: 10.w),
                    // 用户名和日期
                    Expanded(
                      child: [
                        Text(
                          author?.username ?? 'Unknown',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w700,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w700,
                                ).fontFamily,
                            color: Colors.black87,
                          ),
                        ),
                        Text(
                          _formatDate(post.timestamp),
                          style: TextStyle(
                            fontSize: 12.sp,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily,
                            color: Colors.black54,
                          ),
                        ),
                      ].verticalShot(
                        crossAxisAlignment: CrossAxisAlignment.start,
                      ),
                    ),
                    // 导航按钮
                    GestureDetector(
                      onTap: () async {
                        await Navigator.of(context).pushNamed(
                          Routes.momentDetail,
                          arguments: {'postId': post.id},
                        );
                        await viewModel.refresh();
                      },
                      child: Container(
                        width: 32.w,
                        height: 32.w,
                        decoration: BoxDecoration(
                          color: ColorConstants.blueColor,
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Icon(
                          Icons.arrow_forward,
                          color: Colors.white,
                          size: 16.w,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 12.h),
                // 内容文字
                Text(
                  post.content,
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    color: Colors.black87,
                    height: 1.5,
                  ),
                  maxLines: 4,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(height: 12.h),
                // 图片预览（显示三张图片）
                if (post.images.isNotEmpty)
                  Row(
                    children: [
                      for (int i = 0; i < post.images.length && i < 3; i++) ...[
                        Expanded(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(6.r),
                            child: Image.asset(
                              post.images[i],
                              width: double.infinity,
                              height: 105.w,
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        if (i < post.images.length - 1 && i < 2)
                          SizedBox(width: 4.w),
                      ],
                    ],
                  ),
                const Spacer(),
                // 底部操作栏
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    // 点赞和评论
                    Row(
                      children: [
                        // 点赞按钮（已点赞状态）
                        Row(
                          children: [
                            Icon(Icons.favorite, size: 18.w, color: Colors.red),
                            SizedBox(width: 4.w),
                            Text(
                              '${viewModel.getLikeCount(post.id)}',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: Colors.black87,
                              ),
                            ),
                          ],
                        ),
                        SizedBox(width: 16.w),
                        // 评论
                        Row(
                          children: [
                            Image.asset(
                              'assets/images/comment.png',
                              width: 18.w,
                              height: 18.w,
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              '12',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: Colors.black87,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    return '${date.year}.${date.month.toString().padLeft(2, '0')}.${date.day.toString().padLeft(2, '0')}';
  }
}
